package com.project.class4_8.proxyMarke.service.impl;

import com.project.class4_8.proxyMarke.dao.impl.BaseDao;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/**
 * 服务代理类
 */
public class ServiceProxy implements InvocationHandler {
    private Object targetObj;
    public ServiceProxy(Object targetObj){
        this.targetObj=targetObj;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(
                targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(),
                this
        );
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Field [] fields =  targetObj.getClass().getDeclaredFields();
        //得到连接对象
        Connection con=BaseDao.getConnection();
        //设置提交方式为手动提交
        con.setAutoCommit(false);

        for (Field f:fields){
            f.setAccessible(true);
            //得到目标对象属性的值
            Object object=f.get(targetObj);
            //判断属性是否为持久组件
            if (object instanceof BaseDao){
                BaseDao baseDao=(BaseDao) object;
                baseDao.setConnection(con);
            }
        }
        try {
            Object obj = method.invoke(targetObj, args);
            con.commit();
            return obj;
        }catch (Exception e){
            e.printStackTrace();
            con.rollback();
        }finally {
            con.close();
        }
        return null;
    }
}
